import numpy, pandas
from . import models
import re
from django.core.exceptions import ObjectDoesNotExist
import itertools, numpy as np  # 排列组合工具
from django.db.models import Q, Max


# 根据期数匹配中奖信息,并返回列表
def check_bonus(phase_num):
    try:
        checking = models.note_data.objects.filter(phasenum=phase_num)  # get如查询不到，会抛出doesnoexist异常,filter不会
    except ObjectDoesNotExist:
        return None

    for che in checking:
        if not (che.ischeck):
            models.note_data.objects.filter(id=che.id).update(bonuslevel=check_one_note(che))
            models.note_data.objects.filter(id=che.id).update(ischeck=True)
    checking = models.note_data.objects.filter(phasenum=phase_num)
    return checking


# 计算奖金
def calculate_bonus(lottery, firstprice, secondprice):
    total_bonus = 0
    for i in lottery:
        if not (i.bonuslevel == '未中奖'):
            if i.bonuslevel == '一等奖':
                single_bonus = re.sub("\D", "", firstprice)
                total_bonus = total_bonus + int(single_bonus)
            if i.bonuslevel == '二等奖':
                single_bonus = re.sub("\D", "", secondprice)
                total_bonus = total_bonus + int(single_bonus)

            if not ((i.bonuslevel == '一等奖') or (i.bonuslevel == '二等奖')):
                tmp = i.bonuslevel
                single_bonus = models.reward_conditions.objects.filter(bonuslevel=tmp)
                try:
                    single_bonus = models.reward_conditions.objects.filter(bonuslevel=tmp)  # get如查询不到，会抛出doesnoexist异常
                except ObjectDoesNotExist:
                    single_bonus = 0  # 找不到默认为0
                single_bonus = single_bonus[0].single_bonus
                total_bonus = total_bonus + int(single_bonus)
    return total_bonus


# 检测某注是否中奖，使用数据库元数据检测
def check_one_note(one_note):
    redcheck = 0
    bluecheck = 0
    try:
        kailist = models.phase_data.objects.filter(phasenum=one_note.phasenum)  # get如查询不到，会抛出doesnoexist异常
    except ObjectDoesNotExist:
        return '未中奖'

    for kaijiang in kailist:
        redlist = []
        bluelist = []
        redlist.append(kaijiang.red1)
        redlist.append(kaijiang.red2)
        redlist.append(kaijiang.red3)
        redlist.append(kaijiang.red4)
        redlist.append(kaijiang.red5)
        bluelist.append(kaijiang.blue1)
        bluelist.append(kaijiang.blue2)

        if (one_note.red1 in redlist):  redcheck += 1
        if (one_note.red2 in redlist):  redcheck += 1
        if one_note.red3 in redlist:  redcheck += 1
        if one_note.red4 in redlist:  redcheck += 1
        if one_note.red5 in redlist:  redcheck += 1
        if one_note.blue1 in bluelist: bluecheck += 1
        if one_note.blue2 in bluelist: bluecheck += 1

        try:
            checktmp = models.reward_conditions.objects.get(red=redcheck, blue=bluecheck)  # get如查询不到，会抛出doesnoexist异常
            return checktmp.bonuslevel
        except ObjectDoesNotExist:
            break
    return '未中奖'  # 默认返回0


# 根据输入的redlist和bluelist生成投注组合数组，适合单注投注和胆拖
def combinations_notes(redlist, bluelist):
    notelist = []
    for red in itertools.combinations(redlist, 5):  # 从投注的红球中选5个
        for blue in itertools.combinations(bluelist, 2):  # 从投注的蓝球中选2个
            note = red + blue
            notelist.append(note)
    return notelist


# 胆拖组合
def dantuo_combinations_notes(dan_red, tuo_red, dan_blue, tuo_blue):
    notelist = []
    for red in itertools.combinations(tuo_red, 5 - len(dan_red)):
        for blue in itertools.combinations(tuo_blue, 2 - len(dan_blue)):
            # 先排序，再返回
            redsort = tuple(dan_red) + tuple(red)
            redsort = list(redsort)
            redsort.sort()
            redsort = tuple(redsort)

            bluesort = tuple(dan_blue) + tuple(blue)
            bluesort = list(bluesort)
            bluesort.sort()
            bluesort = tuple(bluesort)
            tem = redsort + bluesort  # TODO：元组元素个数为1时，会自动在后面添加一个，空元素，以区别于其他数据，这个要注意
            notelist.append(tem)
    return notelist


# 将投注信息写入数据库，都可以调用该函数写入
def save_notedata_to_DB(phasenum, notelist):
    if not (notelist == []):
        note_list_db = []
        for note in notelist:
            tmp_note_data = models.note_data()
            tmp_note_data.phasenum = phasenum
            tmp_note_data.red1 = note[0]
            tmp_note_data.red2 = note[1]
            tmp_note_data.red3 = note[2]
            tmp_note_data.red4 = note[3]
            tmp_note_data.red5 = note[4]
            tmp_note_data.blue1 = note[5]
            tmp_note_data.blue2 = note[6]
            note_list_db.append(tmp_note_data)
        if not (note_list_db == []):
            models.note_data.objects.bulk_create(note_list_db)  # 将投注信息写入数据库


# 查询最近一期中奖信息,并返回中奖信息
def query_recent_bonue_info():
    recent_phase = models.note_data.objects.filter(~Q(bonuslevel='未中奖')).aggregate(Max('phasenum'))
    if recent_phase['phasenum__max'] is None:  # __max是aggregate函数自动添加的后缀，注意是两个下划线。如果用count则是date__count
        return ''
    else:
        maxphase = recent_phase['phasenum__max']

    record = models.note_data.objects.filter(~Q(bonuslevel='未中奖'), phasenum=maxphase);
    b = np.zeros((9), dtype=np.int)  # 共有九级奖励，从0-8分别为一等奖至九等奖
    for r in record:
        if r.bonuslevel == '一等奖':
            b[0] = b[0] + 1
        if r.bonuslevel == '二等奖':
            b[1] = b[1] + 1
        if r.bonuslevel == '三等奖':
            b[2] = b[2] + 1
        if r.bonuslevel == '四等奖':
            b[3] = b[3] + 1
        if r.bonuslevel == '五等奖':
            b[4] = b[4] + 1
        if r.bonuslevel == '六等奖':
            b[5] = b[5] + 1
        if r.bonuslevel == '七等奖':
            b[6] = b[6] + 1
        if r.bonuslevel == '八等奖':
            b[7] = b[7] + 1
        if r.bonuslevel == '九等奖':
            b[8] = b[8] + 1
    returnstr = '恭喜' + maxphase + '期中：'
    for i in range(len(b)):
        if b[i] > 0:
            returnstr = returnstr + str(i + 1) + '等奖' + str(b[i]) + '注；'
    return returnstr
